package labox.innovation.gameserver.model;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import labox.innovation.config.Config;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class WorldMap {

	private static HashMap<Integer, WorldScence> _scenePool = new HashMap<Integer, WorldScence>();

	private static HashMap<Integer, Point> _pointPool = new HashMap<Integer, Point>();

	private static byte[] _worldMapRawData;

	public static final WorldScence getScener(int id) {
		return _scenePool.get(id);
	}

	public static final Point getPoint(int id) {
		return _pointPool.get(id);
	}

	public static final byte[] getMapData()
	{
		return _worldMapRawData;
	}
	
	public static void fromXMLFile() throws Exception {
		File file = new File(Config.DATAPACK_ROOT, "/WorldMap/worldmap.xml");
		FileInputStream fin = new FileInputStream(file);
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(fin);
		Element root;
		root = document.getDocumentElement();
		if (root.getTagName().compareTo("WorldMap") != 0) {
			throw new Exception("Not a WorldMap file!");
		}
		fromXML(root);
		fin.close();
	}

	public static final void fromXML(Element _root) {
		try {

			ByteArrayOutputStream bais = new ByteArrayOutputStream();
			DataOutputStream dos = new DataOutputStream(bais);
			Element e;
			int i;
			WorldScence scene;
			NodeList nl = (NodeList) _root.getElementsByTagName("Road");
			int count = 0;
			for (i = -1; ++i < nl.getLength();) {
				e = (Element) nl.item(i);
				if (e.getParentNode() != _root)
					continue;
				count++;
			}
			dos.write(count);
			for (i = -1; ++i < nl.getLength();) {
				e = (Element) nl.item(i);
				if (e.getParentNode() != _root)
					continue;
				Point.fromXML(e, _pointPool, dos);
			}

			nl = (NodeList) _root.getElementsByTagName("Scene");
			count = 0;
			for (i = -1; ++i < nl.getLength();) {
				e = (Element) nl.item(i);
				if (e.getParentNode() != _root)
					continue;
				count++;
			}
			dos.write(count);
			for (i = -1; ++i < nl.getLength();) {
				e = (Element) nl.item(i);
				if (e.getParentNode() != _root)
					continue;
				scene = new WorldScence();
				scene.fromXML(e, _scenePool, _pointPool, dos);
			}
			_worldMapRawData = bais.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class ExchangeScene {
	int moveToSceneID;

	int moveToSceneX;

	int moveToSceneY;
}
